from django.db import models

from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from users.models import Company

from utils.validator import validate_memory


def default_company():
    return Company.objects.get_or_create(name="好活（昆山）网络科技有限公司")


class BaseAssetModel(models.Model):
    STATUS_CHOICES = (
        ('used', '使用中'),
        ('idle', '闲置')
    )
    asset_num = models.CharField("资产编号", max_length=128, null=True, blank=True, unique=True)
    sn = models.CharField("SN", max_length=128, unique=True, null=True, blank=True)
    model = models.CharField("型号", max_length=128, null=True, blank=True)
    vendor = models.CharField("制造商/品牌", max_length=64, null=True, blank=True)
    username = models.CharField("负责人", max_length=64, blank=True, null=True)
    department = models.CharField("部门", max_length=64, blank=True, null=True)
    status = models.CharField("状态", choices=STATUS_CHOICES, default='used', max_length=8)
    comment = models.TextField("备注", default='', blank=True)
    location = models.CharField("公司", max_length=256, default='', blank=True)
    buy_date = models.DateField("购买时间", null=True, blank=True)
    updated = models.DateTimeField("更新时间", auto_now=True)
    created = models.DateTimeField("创建时间", auto_now_add=True)
    history = AuditlogHistoryField()

    class Meta:
        abstract = True


class Hosts(BaseAssetModel):
    NOTEBOOK, DESKTOP, ALL_IN_ONE, CLOUD_DESKTOP = 'N', 'D', 'AIO', 'CD'
    UNKNOWN = ('U', '未知')
    TYPE_CHOICES = (
        (NOTEBOOK, '笔记本'),
        (DESKTOP, '台式机'),
        (ALL_IN_ONE, '一体机'),
        (CLOUD_DESKTOP, '云桌面'),
        UNKNOWN
    )
    tp = models.CharField("类型", choices=TYPE_CHOICES, default=NOTEBOOK, max_length=8)
    cpu = models.CharField("CPU", max_length=128, null=True, blank=True)
    memory = models.PositiveSmallIntegerField("内存", validators=[validate_memory], null=True, blank=True)
    company = models.ForeignKey(Company, on_delete=models.SET(default_company), verbose_name="公司",
                                null=True, blank=True, related_name="hosts")
    class Meta:
        db_table = 'computer'
        verbose_name = '电脑'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.asset_num}-{self.vendor} {self.model}'

    @property
    def get_disks(self):
        disks = self.disks.all()
        s = ''
        for disk in disks:
            capacity = f'{disk.capacity}GB'
            if disk.capacity > 1024:
                capacity = f'{int(disk.capacity / 1024)}TB'
            s += f'{capacity}+'
        return s.strip('+')

    get_disks.fget.short_description = '硬盘'

    @property
    def get_memory(self):
        if self.memory:
            return f'{self.memory}GB'

    get_memory.fget.short_description = '内存'


class Disks(models.Model):
    HDD, SSD = 'hdd', 'ssd'
    DISK_TYPE = (
        (HDD, '机械硬盘'),
        (SSD, '固态硬盘')
    )
    capacity = models.PositiveSmallIntegerField('容量(GB)')
    tp = models.CharField('类型', choices=DISK_TYPE, max_length=8, default=SSD)
    vendor = models.CharField("制造商/品牌", max_length=64, null=True, blank=True)
    host = models.ForeignKey(Hosts, models.CASCADE, verbose_name='所属计算机', related_name="disks")
    created = models.DateTimeField("创建时间", auto_now_add=True)

    class Meta:
        db_table = 'disks'
        verbose_name = '硬盘'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.host.__str__()}-{self.get_tp_display()}:{self.capacity}GB'


class Network(models.Model):
    """
    network interface card
    """
    mac = models.CharField("Mac地址", max_length=32)
    name = models.CharField("网卡名", max_length=128, null=True, blank=True)
    speed = models.SmallIntegerField("带宽(Mb/s)", default=1000)
    mtu = models.IntegerField("MTU", default=1500, null=True, blank=True)
    ip = models.GenericIPAddressField("IP地址", null=True, blank=True)
    host = models.ForeignKey(Hosts, models.CASCADE, verbose_name='所属计算机', related_name="nics")
    created = models.DateTimeField("创建时间", auto_now_add=True)

    class Meta:
        db_table = 'network'
        verbose_name = '网卡'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.mac


class Accessories(BaseAssetModel):
    MON, MOU, KB = 'monitor', 'mouse', 'keyboard'
    TYPE_CHOICES = (
        (MON, '显示器'),
        (MOU, '鼠标'),
        (KB, '键盘')
    )
    tp = models.CharField('类型', max_length=16, default=MON, choices=TYPE_CHOICES)
    company = models.ForeignKey(Company, on_delete=models.SET(default_company), verbose_name="公司",
                                null=True, blank=True, related_name="accessories")
    history = AuditlogHistoryField()

    class Meta:
        db_table = 'accessories'
        verbose_name = '配件'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.asset_num}-{self.tp}-{self.vendor} {self.model}'


auditlog.register(Hosts)
auditlog.register(Disks)
auditlog.register(Network)
auditlog.register(Accessories)
